package qeug.shsh.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.entity.datamodel.events.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

/**
 * 分摊成本中心过滤和赋值逻辑
 * 使用单据：差旅报销单，费用报销单，付款申请单
 */
public class AllocationCostCenterFilter extends AbstractFormPlugin implements BeforeF7SelectListener {
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit std_entrycostcenter_crule = this.getView().getControl("std_entrycostcenter_crule");//分摊成本中心
        std_entrycostcenter_crule.addBeforeF7SelectListener(this);
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        String name = this.getModel().getDataEntityType().getName();//单据标识
        String entryName = e.getEntryProp().getName();//新增行单据体名
        if ("expenseentryentity_rule".equals(entryName)) {
            //分摊明细分录新增行
            RowDataEntity[] rowDataEntities = e.getRowDataEntities();
            for (RowDataEntity rowDataEntity : rowDataEntities) {
                int rowIndex = rowDataEntity.getRowIndex();
                int parentRowIndex = rowDataEntity.getParentRowIndex();
                DynamicObject dataEntity = rowDataEntity.getDataEntity();
                DynamicObject costDept = dataEntity.getDynamicObject("entrycostdept_orgrule");//费用承担部门
                DynamicObject costCompany = dataEntity.getDynamicObject("entrycostcompany_orgrule");//费用承担公司
                if (costDept == null || costCompany == null) {
                    this.getModel().setValue("std_entrycostcenter_crule", null);
                    return;
                }
                QFilter qFilter1 = new QFilter("qeug_org.number", QCP.equals, costDept.getString("number"));
                DynamicObject bos_costcentersourcemap = BusinessDataServiceHelper.loadSingle("qeug_costcenter_org", new QFilter[]{qFilter1});//成本中心部门配置
                if (bos_costcentersourcemap == null) {
                    this.getModel().setValue("std_entrycostcenter_crule", null);
                    return;
                }
                DynamicObjectCollection entryEntityCollection = bos_costcentersourcemap.getDynamicObjectCollection("qeug_entryentity");//分录
                List<String> costCenterNumbers = new ArrayList<>();
                for (DynamicObject entryEntity : entryEntityCollection) {
                    DynamicObject costCenter1 = entryEntity.getDynamicObject("qeug_costcenter");//成本中心
                    DynamicObject accountOrg = costCenter1.getDynamicObject("accountorg");//对应核算组织
                    if (accountOrg != null && accountOrg.getString("number") != null && accountOrg.getString("number").equals(costCompany.getString("number"))) {
                        String number = costCenter1.getString("number");
                        if (number != null && !number.isEmpty()) {
                            costCenterNumbers.add(number);
                        }
                    }
                }
                if (costCenterNumbers.size() != 1) {
                    this.getModel().setValue("std_entrycostcenter_crule", null);//成本中心
                } else {
                    QFilter qFilter2 = new QFilter("number", QCP.equals, costCenterNumbers.get(0));
                    DynamicObject bos_costcenter = BusinessDataServiceHelper.loadSingle("bos_costcenter", "id", new QFilter[]{qFilter2});//成本中心
                    this.getModel().setValue("std_entrycostcenter_crule", bos_costcenter);//成本中心
                }
                this.getView().updateView("expenseentryentity_rule");
            }
        }
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String fieldKey = e.getProperty().getName();
        if ("entrycostdept_orgrule".equals(fieldKey) || "entrycostcompany_orgrule".equals(fieldKey)) {
            //费用承担部门，费用承担公司
            ChangeData changeData = e.getChangeSet()[0]; //修改值所在行
            DynamicObject dataEntity = changeData.getDataEntity(); //修改值所在行数据
            int rowIndex = changeData.getRowIndex(); //修改行所在行行号
            DynamicObject costDept = null;
            DynamicObject costCompany = null;
            if ("entrycostdept_orgrule".equals(fieldKey)){
                costDept = (DynamicObject) changeData.getNewValue();//费用承担部门
                costCompany = dataEntity.getDynamicObject("entrycostcompany_orgrule");//费用承担公司
            }else{
                costCompany = (DynamicObject) changeData.getNewValue();//费用承担公司
                costDept = dataEntity.getDynamicObject("entrycostdept_orgrule");//费用承担部门
            }
            if (costDept == null || costCompany == null) {
                this.getModel().setValue("std_entrycostcenter_crule", null ,rowIndex);//成本中心
                return;
            }
            QFilter qFilter1 = new QFilter("qeug_org.number", QCP.equals, costDept.getString("number"));
            DynamicObject bos_costcentersourcemap = BusinessDataServiceHelper.loadSingle("qeug_costcenter_org", new QFilter[]{qFilter1});//成本中心部门配置
             if (bos_costcentersourcemap == null) {
                this.getModel().setValue("std_entrycostcenter_crule", null ,rowIndex);//成本中心
                return;
            }
            DynamicObjectCollection entryEntityCollection = bos_costcentersourcemap.getDynamicObjectCollection("qeug_entryentity");//分录
            List<String> costCenterNumbers = new ArrayList<>();
            for (DynamicObject entryEntity : entryEntityCollection) {
                DynamicObject costCenter1 = entryEntity.getDynamicObject("qeug_costcenter");//成本中心
                DynamicObject accountOrg = costCenter1.getDynamicObject("accountorg");//对应核算组织
                if (accountOrg != null && accountOrg.getString("number") != null && accountOrg.getString("number").equals(costCompany.getString("number"))) {
                    String number = costCenter1.getString("number");
                    if (number != null && !number.isEmpty()) {
                        costCenterNumbers.add(number);
                    }
                }
            }
            if (costCenterNumbers.size() != 1) {
                this.getModel().setValue("std_entrycostcenter_crule", null, rowIndex);//成本中心
            } else {
                QFilter qFilter2 = new QFilter("number", QCP.equals, costCenterNumbers.get(0));
                DynamicObject bos_costcenter = BusinessDataServiceHelper.loadSingle("bos_costcenter", "id", new QFilter[]{qFilter2});//成本中心
                this.getModel().setValue("std_entrycostcenter_crule", bos_costcenter, rowIndex);//成本中心
            }
            this.getView().updateView("expenseentryentity_rule");
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
        ListShowParameter formShowParameter = (ListShowParameter) beforeF7SelectEvent.getFormShowParameter();
        List<QFilter> qFilter = new ArrayList<>();
        DynamicObject costDept = (DynamicObject) this.getModel().getValue("entrycostdept_orgrule");//费用承担部门
        DynamicObject costCompany = (DynamicObject) this.getModel().getValue("entrycostcompany_orgrule");//费用承担公司
        if (costDept == null || costCompany == null) {
            return;
        }
        QFilter qFilter1 = new QFilter("qeug_org.number", QCP.equals, costDept.getString("number"));
        DynamicObject bos_costcentersourcemap = BusinessDataServiceHelper.loadSingle("qeug_costcenter_org", new QFilter[]{qFilter1});//成本中心部门配置
        if (bos_costcentersourcemap == null) {
            qFilter.add(new QFilter("number", QCP.equals, "00000000000"));
            formShowParameter.getListFilterParameter().setQFilters(qFilter);
            return;
        }
        DynamicObjectCollection entryEntityCollection = bos_costcentersourcemap.getDynamicObjectCollection("qeug_entryentity");//分录
        List<String> costCenterNumbers = new ArrayList<>();
        for (DynamicObject entryEntity : entryEntityCollection) {
            DynamicObject costCenter1 = entryEntity.getDynamicObject("qeug_costcenter");//成本中心
            DynamicObject accountOrg = costCenter1.getDynamicObject("accountorg");//对应核算组织
            if (accountOrg != null && accountOrg.getString("number") != null && accountOrg.getString("number").equals(costCompany.getString("number"))) {
                String number = costCenter1.getString("number");
                if (number != null && !number.isEmpty()) {
                    costCenterNumbers.add(number);
                }
            }
        }
        if (!costCenterNumbers.isEmpty()) {
            qFilter.add(new QFilter("number", QCP.in, costCenterNumbers.toArray()));
            formShowParameter.getListFilterParameter().setQFilters(qFilter);
        } else {
            qFilter.add(new QFilter("number", QCP.equals, "00000000000"));
            formShowParameter.getListFilterParameter().setQFilters(qFilter);
        }
    }
}
